package org.mango.id;

import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * Created by meigang on 17/8/28.
 */
public class Tools {
    private static SnowflakeIdWorker snowflakeIdWorker = null;
    private static Key _globalKey = null;

    /**
     * 生成 uuid
     * @return
     */
    public static String genUuid(){
        String uuid = UUID.randomUUID().toString();
        uuid = uuid.replaceAll("-","");
        return uuid;
    }

    public static synchronized long genId() {
        if(snowflakeIdWorker == null) {
            snowflakeIdWorker = new SnowflakeIdWorker((long)0, (long)0);
        }

        return snowflakeIdWorker.nextId();
    }

    public static byte[] stringToBytes(String str) {
        try {
            return str.getBytes("UTF-8");
        } catch (Exception var2) {
            var2.printStackTrace();
            return null;
        }
    }

    public static String bytesToString(byte[] bytes) {
        if(bytes != null && bytes.length >= 1) {
            try {
                return new String(bytes, "UTF-8");
            } catch (Exception var2) {
                var2.printStackTrace();
                return "";
            }
        } else {
            return null;
        }
    }

    public static String getMd5(String plainText) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            //打印生成的MD5加密信息摘要
            System.out.println(buf.toString().substring(8, 24));
            //32位加密
            // return buf.toString();
            // 16位的加密
            return buf.toString().substring(8, 24);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }

    }

}
